<?php

namespace Bigspender\DefaultBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\Loader\ArrayLoader;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Bigspender\DefaultBundle\Form\SignUpType;
use Bigspender\DefaultBundle\Entity\SignUp;
use Bigspender\DefaultBundle\Entity\User;
use Doctrine\DBAL\DBALException;


class DefaultController extends Controller
{
	/**
	 * @Route("/", name="_index")
	 */
    public function indexAction()
    {
        return $this->render('BigspenderDefaultBundle:Default:index.html.twig', array());
    }

	/**
	 * @Route("/sign-up", name="_sign_up")
	 */
    public function signUpAction(Request $request)
    {
        $signup = new SignUp();
        $form = $this->createForm(new SignUpType(), $signup);
        $form->handleRequest($request);
        $translator = $this->get('translator');
        $flashBag = $this->get('session')->getFlashBag();
        if ($form->isValid()) {
            try {
                $user = new User();
                $user->setFromSignUp($signup);
                $user->setHash(md5($user->getId()));
                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();

                $from = $this->container->getParameter('contact_email');

                $message = \Swift_Message::newInstance()
                    ->setContentType('text/html')
                    ->setSubject($translator->trans('SIGN UP EMAIL SUBJECT'))
                    ->setFrom($from)
                    ->setTo($signup->getEmail())
                    ->setBody($this->renderView(
                        'BigspenderDefaultBundle:Default:email.html.twig', 
                        array('name' => 'joee', 'hash' => $user->getHash())));
                
                $success = $this->get('mailer')->send($message);
                $flashBag->setName('success');
                $flashBag->add('message', $translator->trans('SIGN UP EMAIL SENT'));
            }
            catch (\Exception $e) {
                $flashBag->setName('error');
                $flashBag->add('message', $translator->trans('SIGN UP ERROR'));                    
            }
        }
        else if ($form->isSubmitted()) {
            $flashBag->setName('error');
            $flashBag->add('message', $translator->trans('CREATE MOVIMENTATION FORM ERROR'));                               
        }
        
        return $this->render('BigspenderDefaultBundle:Default:signup.html.twig', array('form' => $form->createView()));
    }

}
